package cn.ty.znsz.role;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;

import cn.ty.znsz.common.model.SysRole;
import cn.ty.znsz.common.model.SysRolePoint;

public class RoleService {
	private SysRole roleDao=new SysRole().dao();
	
	/**
	 * 得到所有角色
	 * @return
	 */
	public Ret getAllRoles(String cookie) {
		String key=Redis.use().get(cookie);
		String roleIds=Redis.use().hget(key, "roleIds");
		String childRoleIds=Db.queryStr("SELECT GROUP_CONCAT(a.childIds) roles from sys_role a WHERE a.id IN ("+roleIds+");");
		List<SysRole> roles=roleDao.find("SELECT a.id,a.`name` roleName from sys_role a WHERE a.id IN ("+childRoleIds+") order by a.sortOrder;");
		return Ret.ok("操作成功").set("data", roles);
	}
	
	/**
	 * 分页
	 * @param paraToInt
	 * @param paraToInt2
	 * @param para
	 * @return
	 */
	public Page<SysRole> paginate(Integer pageNumber, Integer pageSize, String roleName) {
		String select="select * ";
		StringBuilder sql = new StringBuilder();
		sql.append("from sys_role a where 1=1");
		if(!"".equals(roleName) && roleName !=null){
			sql.append(" and a.name like '%"+roleName+"%'");
		}
		sql.append(" ORDER BY a.sortOrder");
		return roleDao.paginate(pageNumber, pageSize, select, sql.toString());
	}
	/**
	 * 添加角色保存
	 * @param data
	 * @return
	 */
	public Ret roleSave(SysRole data) {
		data.setCreateAt(new Date());
		data.use("zsql").save();
		return Ret.ok("操作成功");
	}
	/**
	 * 修改角色保存
	 * @param data
	 * @param paraToInt
	 * @return
	 */
	public Ret roleUpdate(SysRole data, Integer id) {
		data.setId(id);
		data.use("zsql").update();
		return Ret.ok("操作成功");
	}
	/**
	 * 删除角色
	 * @param paraToInt
	 * @return
	 */
	public Ret roleDel(Integer id) {
		new SysRole().use("zsql").deleteById(id);
		return Ret.ok("操作成功");
	}
	/**
	 * 后台角色授权
	 * @param paraToInt
	 * @return
	 */
	public Ret powerWeb(Integer id) {
		//查询所有的菜单
		List<Record> allMenus = Db.find("SELECT DISTINCT a.id,a.title,a.parentId,a.sortOrder from sys_menu a ORDER BY a.sortOrder;");
		//查询所有的增删改按钮power菜单
		List<Record> allPowers = Db.find("SELECT CONCAT('p-',a.id) id,a.pointName title,a.menuId parentId,a.sortOrder from sys_menu_point a ORDER BY a.sortOrder;");
		 //查询该角色对应的菜单
	    List<Record> rolePowers=Db.find("SELECT CONCAT('p-',b.id) id FROM sys_role_point a LEFT JOIN sys_menu_point b ON a.pointId=b.id WHERE a.roleId=?",id);
	    //设置选中
	    for(Record rc:allPowers){
	    	for(Record rec:rolePowers){
	    		if(rc.getStr("id").equals(rec.getStr("id"))){
	    			rc.set("checked", true);
	    		}
	    	}
	    }
		//合并
		allMenus.addAll(allPowers);
		//得到所有根节点
		List<Record> rootMenus = new ArrayList<Record>();
		for(Record rc:allMenus){
			if(rc.getInt("parentId")==0){//父节点是0的，为根节点。
					rootMenus.add(rc);
		        }
		}
		//为根菜单设置子菜单，getClild是递归调用的
	      for (Record rc : rootMenus) {
	        /* 获取根节点下的所有子节点 使用getChild方法*/
	        List<Record> childList = this.getChild(rc.getStr("id"), allMenus);
	        rc.set("children", childList);//给根节点设置子节点
	      }
	    return Ret.ok("操作成功！").set("data", rootMenus);
	}
	/**
	 * 递归获取子节点方法
	 * @param id 父节点id
	 * @param allMenus 所有菜单列表
	 * @return 每个根节点下，所有子菜单列表
	 */
	public List<Record> getChild(String id,List<Record> allMenus){
	    //子菜单
	    List<Record> childList = new ArrayList<Record>();
	    for (Record rc : allMenus) {
	      // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
	      //相等说明：为该根节点的子节点。
	      if(rc.getStr("parentId").equals(id)){
	        childList.add(rc);
	      }
	    }
	    //递归
	    for (Record rc : childList) {
	    	rc.set("children", getChild(rc.getStr("id"), allMenus));
	    }
	    //如果节点下没有子节点，返回一个空List（递归退出）
	    if(childList.size() == 0){
	      return null;
	    }
	    return childList;
	  }
	/**
	 * 后台角色授权保存
	 * @param para
	 * @param para2
	 * @return
	 */
	public Ret savePowerWeb(String checkData, int roleId) {
		//利用正则表达式提取p-和"之间的数据
		String rgex = "p-(.*?)\"";
		List<String> list = new ArrayList<String>();
		Pattern pattern = Pattern.compile(rgex);
		Matcher m = pattern.matcher(checkData);
		while (m.find()) {
            int i = 1;
            list.add(m.group(i));
            i++;
        }
		Db.tx(() -> {
				Db.use("zsql").update("delete from sys_role_point where roleId = (" + roleId + ")");
				for(int i=0;i<list.size();i++){
					SysRolePoint srp=new SysRolePoint();
					srp.setRoleId(roleId);
					srp.setPointId(Integer.parseInt(list.get(i)));
					srp.use("zsql").save();
				}
			  return true;
			});	
		return Ret.ok("操作成功！");
	}	
	
}
